

var db = require('../db');
var webResult = require('../web-result');
var jwt = require('jsonwebtoken');
var router = require('express').Router();





router.get('/user/verifyToken', async (_request, response) => {
	response.send(webResult.success(true));
});


router.get('/user/id/:id', async function(request, response, next) {
  	const uid = request.params.id;

	db.query("select * from user where id = ?", [uid])
	.then(res => {
		if (!res[0])
		{
			response.send(webResult.failed());
			return;
		}
		res[0].register_time = `${res[0].register_time.getFullYear()}/${(res[0].register_time.getMonth() + 1)}/${res[0].register_time.getDate()}`;
		res[0].password = undefined;
		res[0].email = undefined;
		res[0].phone = undefined;
		response.send(webResult.success(res[0]));
	})
});


router.get('/user/username/:username', async function(request, response, _next) {
	const username = request.params.username;

	db.query("select * from user where username = ?", [username])
	.then(res => {
		if (!res[0])
		{
			response.send(webResult.failed());
			return;
		}
		res[0].register_time = `${res[0].register_time.getFullYear()}/${(res[0].register_time.getMonth() + 1)}/${res[0].register_time.getDate()}`;
		res[0].password = undefined;
		res[0].email = undefined;
		res[0].phone = undefined;
		response.send(webResult.success(res[0]));
	})
});



router.get('/user/search/nickname/:nickname/page/:page', async (request, response) => {
	const { nickname, page } = request.params;

	db.query("select * from user where nickname like ? limit ?, ?", [nickname, pageSize * (page - 1), pageSize])
	.then(res => {
		res.forEach(element => {
			element.register_time = `${element.register_time.getFullYear()}/${(element.register_time.getMonth() + 1)}/${element.register_time.getDate()}`;
			element.password = undefined;
			element.email = undefined;
			element.phone = undefined;
		});
		response.send(webResult.success(res));
	})
});


router.get('/user/search/username/:username/page/:page', async (request, response) => {
	const { username, page } = request.params;

	db.query("select * from user where username like ? limit ?, ?", [username, pageSize * (page - 1), pageSize])
	.then(res => {
		res.forEach(element => {
			element.register_time = `${element.register_time.getFullYear()}/${(element.register_time.getMonth() + 1)}/${element.register_time.getDate()}`;
			element.password = undefined;
			element.email = undefined;
			element.phone = undefined;
		});
		response.send(webResult.success(res));
	})
});



const registerUser = async (request, response) => {
	// console.log("params: ", request.params);
	// console.log("body: ", request.body);

	const { username, password } = request.body;
	let { nickname } = request.body;
	if (!username)
	{
		response.send(webResult.failed("!username"));
		return;
	}
	if (!password)
	{
		response.send(webResult.failed("!password"));
		return;
	}
	if (!nickname)
	{
		nickname = username;
	}

	const checkSelectArray = [
		db.query("select id from user where username = ?", [username]),
		db.query("select id from user where nickname = ?", [nickname])
	];

	Promise.all(checkSelectArray)
	.then(resultArray => {
		if (resultArray[0][0])
		{
			response.send(webResult.failed("用户名已经被使用"));
			return;
		}
		if (resultArray[1][0])
		{
			response.send(webResult.failed("昵称已经被使用"));
			return;
		}

		db.query("insert into user (nickname, username, password) values(?, ?, ?)", [nickname, username, password])
		.then(res => {
			console.log("insert result: ", res);
			if (res.affectedRows === 0)
			{
				response.send(webResult.failed(undefined, "注册失败"));
				return;
			}
			response.send(webResult.success(undefined, "注册成功"));
		});
	})

};
router.post("/user", registerUser);
router.post("/user/register", registerUser);



router.post("/user/login", async (request, response) => {
	// console.log("params: ", request.params);
	// console.log("body: ", request.body);

	const { username, password } = request.body;
	if (!username)
	{
		response.send(webResult.failed("!username"));
		return;
	}
	if (!password)
	{
		response.send(webResult.failed("!password"));
		return;
	}


	db.query("select * from user where username = ?", [username])
	.then(res => {
		if (!res[0])
		{
			response.send(webResult.failed("用户不存在"));
			return;
		}

		if (res[0].password !== password)
		{
			response.send(webResult.failed("密码错误"));
			return;
		}

		const token = jwt.sign({
			id: res[0].id,
			username: res[0].username
		}, res[0].password, { expiresIn: 36000 });
		response.send(webResult.success(token));
	})
});




router.put('/user', async (request, response) => {
	const token = request.headers.token;
	const { id } = jwt.decode(token);

	let sql = "update user set "
	const user = request.body;
	if (user == {})
	{
		response.send(webResult.failed("更新的内容为空"));
		return;
	}

	if (user.username)
		delete user.username;
	for (key in user)
	{
		if (user[key])
		{
			sql += key + ' = "' + user[key] + '", '
		}
	}
	sql = sql.substring(0, sql.length - 2);
	sql += ' where id = "' + id + '";'
	// console.log("update sql:", sql);

	db.query(sql)
	.then(res => {
		// console.log(res)
		if (res.affectedRows === 0)
		{
			response.send(webResult.failed());
			return;
		}
		response.send(webResult.success(undefined, "修改成功"));
	})
});




module.exports = router;


